import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import * as iconv from 'iconv-lite';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AxiosService {
  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
  }

  /**
   * 获取ip地址
   * @returns {Promise<string>}
   */
  async getIpAddress(ip: string): Promise<string> {
    try {
      const IP_URL = 'https://whois.pconline.com.cn/ipJson.jsp';
      const response = await this.httpService.axiosRef(`${IP_URL}?ip=${ip}&json=true`, {
        responseType: 'arraybuffer',
        transformResponse: [
          function(data) {
            console.log(data);
            // 解决中文乱码问题
            const str = iconv.decode(data, 'gbk');
            return JSON.parse(str);
          },
        ],
      });
      return response.data.addr;
    } catch (error) {
      return '未知';
    }
  }

  async getRequest(url) {
    try {
      const response = await this.httpService.axiosRef.get(url, {
        responseType: 'json',
      });
      return response.data;
    } catch (e) {
      return null;
    }
  }

  async getSwaggerJson() {
    try {
      const prefix = this.configService.get('application.prefix') || '';
      const host = this.configService.get('swagger.host') || 'localhost';
      const basePath = this.configService.get('swagger.basePath') || 'api-docs';
      const IP_URL = `http://${host}${prefix}/${basePath}-json`;

      const response = await this.httpService.axiosRef.get(IP_URL, {
        responseType: 'json',
      });
      return response.data;
    } catch (e) {
      return null;
    }
  }


  /**
   * 将接口数据同步到apifox
   * @param url
   * @param data
   * @returns {Promise<void>}
   */

  async syncApiFox(data) {
    const API_FOX_URL = this.configService.get('swagger.apiFox_url');
    const API_FOX_TOKEN = this.configService.get('swagger.apiFox_token');
    const API_FOX_PROJECT_ID = this.configService.get('swagger.apiFox_project_id');
    const API_FOX_VERSION = this.configService.get('swagger.apiFox_version');
    // 目录id
    const API_FOX_FOLDER_ID = this.configService.get('swagger.apiFox_folder_id');
    if (!API_FOX_URL || !API_FOX_TOKEN || !API_FOX_PROJECT_ID || !API_FOX_VERSION) {
      return;
    }

    try {

      const url = API_FOX_URL.replace('{projectId}', API_FOX_PROJECT_ID);
      console.log('开始同步:同步地址:', url);
      const response = await this.httpService.axiosRef.post(
        url,
        {
          input: JSON.stringify(data),
          options: {
            targetEndpointFolderId: API_FOX_FOLDER_ID,
          },
        },
        {
          headers: {
            Authorization: `Bearer ${API_FOX_TOKEN}`,
            'X-Apifox-Api-Version': API_FOX_VERSION,
          },
        },
      );
      console.log('同步成功，结果为：', response.data);
      return response.data;
    } catch (e) {
      console.log('同步失败');
      return e;

    }
  }
}
